package com.s2bdatautil;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import com.google.gson.Gson;

public class ReadExpressInfo {
	public static final String DATETIME_PATTERN               = "yyyy-MM-dd HH:mm:ss";
	static SimpleDateFormat format = new SimpleDateFormat(DATETIME_PATTERN);
	static Map<String, String> user = new HashMap<String, String>();
	static String userTemple = "D:\\桌面\\ImportData\\注册用户模板.sql";
	static String orederTemple = "D:\\桌面\\ImportData\\用户订单模板.sql";
	static String targetData = "D:\\桌面\\ImportData\\output\\注册用户列表06.sql";

	public static void main(String[] args) throws Exception {
		Map<String, Double[]> sellerLimit = new HashMap<String, Double[]>();
		sellerLimit.put("xz002", new Double[] {12300d, 0d});
		sellerLimit.put("xz003", new Double[] {13000d, 0d});
		sellerLimit.put("xz004", new Double[] {11100d, 0d});
		sellerLimit.put("xz005", new Double[] {10100d, 0d});
		sellerLimit.put("xz006", new Double[] {510300d, 0d});
		sellerLimit.put("xz007", new Double[] {511230d, 0d});
		sellerLimit.put("xz008", new Double[] {720011d, 0d});
		sellerLimit.put("xz009", new Double[] {1601342d, 0d});
		
		List<List<List<String>>> readdata = readExpressFromExcel("D:\\桌面\\ImportData\\20190210.xlsx");
		File file = new File(targetData);
		if(file.exists()) {
			file.delete();
		}
		// 遍歷快遞單，創建用戶及訂單
		int userid = 26436;
		int index = 0;
		for(List<String> exp : readdata.get(0)) {
			boolean exituser = true;
			if(exp.get(4) != null && exp.get(4).startsWith("No:")) {
				System.out.println((index++) + "  " + exp.get(4));
				// 調用快遞api獲取訂單時間
				ExpressObj eobj = readExpressAPI(exp.get(4).replaceAll("No:", ""), exp.get(5));
				String fisrtTime = null;
				String regtime2 = null;
				long reglong = 0l;
				try {
					fisrtTime = eobj.getList().get(eobj.getList().size()-1).getTime();
					regtime2 = addTimeBySeconds(fisrtTime, -1 * randomIntRange(3600, 36000 * 3));
					reglong = format.parse(regtime2).getTime()/1000;
				}catch(Exception e) {
					System.out.println( "快递单号：" + exp.get(4) + " 无效。");
					continue;
				}
				System.out.println(fisrtTime);
				Map<String, String> datamap = new HashMap<String, String>();
				if(!user.containsKey(exp.get(3))) { // 用戶不存在，需要創建用戶
					userid++;
					user.put(exp.get(3), String.valueOf(userid));
					exituser = false;
				}else {
					exituser = true;
				}
				datamap.put("userid", user.get(exp.get(3)));
				datamap.put("username", exp.get(3));
				datamap.put("passport", exp.get(0));
				datamap.put("buyer_mobile", exp.get(3));
				datamap.put("regtime", String.valueOf(reglong));
				// 创建订单
				List<String> order = randomUserData(sellerLimit, readdata.get(1));
				
				datamap.put("mallid", order.get(0));
				datamap.put("seller", order.get(7));
				datamap.put("title", order.get(1));
				datamap.put("thumb", order.get(2));
				datamap.put("price", order.get(6));
				datamap.put("number", randomIntRange(1, 100)>55?randomIntRange(2, 10)+"":"1");
				datamap.put("amount", (Double.parseDouble(datamap.get("price")) * Double.parseDouble(datamap.get("number")))+"");
				datamap.put("buyer_name", datamap.get("username"));
				// 将订单加入 limit 
				if(sellerLimit.size() > 0 && sellerLimit.containsKey(datamap.get("seller"))) {
					if(sellerLimit.get(datamap.get("seller"))[0] < sellerLimit.get(datamap.get("seller"))[1]) {
						sellerLimit.remove(datamap.get("seller"));
						continue;
					}else {
						sellerLimit.get(datamap.get("seller"))[1] = sellerLimit.get(datamap.get("seller"))[1] + Double.parseDouble(datamap.get("amount"));
					}
				}else if(sellerLimit.size() > 0 ) {
					System.out.println(datamap.get("seller") + " 用户数据都刷新完毕！");
					continue;
				}
				if(sellerLimit.size()==0) {
					System.out.println("所有用户数据都刷新完毕！");
					break;
				}
				String addressInfo = exp.get(1);
				String address = addressInfo;
				String postcode = "";
				if(addressInfo.endsWith(")")) {
					address = addressInfo.substring(0, addressInfo.lastIndexOf("("));
					postcode = addressInfo.substring(addressInfo.lastIndexOf("(")+1, addressInfo.length()-1);
				} 
				datamap.put("buyer_address", address);
				datamap.put("buyer_postcode", postcode);
				datamap.put("send_type", exp.get(5));
				datamap.put("send_no", exp.get(4).replaceAll("No:", ""));
				datamap.put("send_time", fisrtTime);
				datamap.put("addtime", String.valueOf(reglong));
				
				writeOrderAndUser(datamap, exituser);
			}
		}
		System.out.println("userid:" + userid);
		for(String key : sellerLimit.keySet()) {
			System.out.println(key + "  " + sellerLimit.get(key)[0] + "   " + sellerLimit.get(key)[1]);
		}
	}
	
	private static List<String> randomUserData(Map<String, Double[]> sellerLimit, List<List<String>> list) {
		int index = randomIntRange(1, list.size());
		List<String> onedataList = list.get(index-1);
		if(sellerLimit.size() > 0 && !sellerLimit.containsKey(onedataList.get(7))) {
			return randomUserData(sellerLimit, list);
		}else {
			return onedataList;
		}
	}

	public static String addTimeBySeconds(String startDate, int seconds) {
		SimpleDateFormat f = new SimpleDateFormat(DATETIME_PATTERN);
		Calendar c = Calendar.getInstance();
		try { 
			c.setTime(f.parse(startDate));
		} catch (Exception e) {
			e.printStackTrace();
		}  
		c.add(Calendar.SECOND, seconds);
		return f.format(c.getTime());
	}
	
	private static void writeOrderAndUser(Map<String, String> datamap, boolean exituser) {
		if(!exituser) {
			String context = readTxtFile(userTemple);
			for(String key : datamap.keySet()) {
				String regex = "${"+key+"}";
				if(context.contains(regex))
					context = context.replace(regex, datamap.get(key));
			}
			printFile(context, targetData);
		}
		String context = readTxtFile(orederTemple);
		for(String key : datamap.keySet()) {
			String regex = "${"+key+"}";
			if(context.contains(regex))
				context = context.replace(regex, datamap.get(key));
		}
		printFile(context, targetData);
		
	}

	private static ExpressObj readExpressAPI(String snno, String expname) {
		ExpressObj result = new ExpressObj();
		String host = "https://cexpress.market.alicloudapi.com";
	    String path = "/cexpress";
	    String method = "GET";
	    String appcode = "e591641e480d472c90d1b75adcebd4e3";
	    Map<String, String> headers = new HashMap<String, String>();
	    //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
	    headers.put("Authorization", "APPCODE " + appcode);
	    Map<String, String> querys = new HashMap<String, String>();
	    querys.put("no", snno);
//	    querys.put("type", "zto");
            //JDK 1.8示例代码请在这里下载：  http://code.fegine.com/Tools.zip


	    try {
	    	/**
	    	* 重要提示如下:
	    	* HttpUtils请从
	    	* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
                * 或者直接下载：
                * http://code.fegine.com/HttpUtils.zip
	    	* 下载
	    	*
	    	* 相应的依赖请参照
	    	* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
                * 相关jar包（非pom）直接下载：
                * http://code.fegine.com/aliyun-jar.zip
	    	*/
	    	HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
	    	//System.out.println(response.toString());如不输出json, 请打开这行代码，打印调试头部状态码。
                //状态码: 200 正常；400 URL无效；401 appCode错误； 403 次数用完； 500 API网管错误
	    	//获取response的body
	    	Gson g = new Gson();
	    	result = g.fromJson(EntityUtils.toString(response.getEntity()), ExpressObj.class);
//	    	System.out.println(EntityUtils.toString(response.getEntity()));
	    } catch (Exception e) {
	    	e.printStackTrace();
	    }
		return result;
	}

	public static int randomIntRange(int MIN, int MAX) {
		// randNumber 将被赋值为一个 MIN 和 MAX 范围内的随机数
		Random rand = new Random();
		int randNumber = rand.nextInt(MAX - MIN + 1) + MIN;
		return randNumber;
	}

	private static List<List<List<String>>> readExpressFromExcel(String fileurl) throws Exception {
		List<List<List<String>>> list = ReadExcel.readXlsx(fileurl);
		
		return list;
	}

	public static String readTxtFile(String filePath) {
		StringBuilder content = new StringBuilder("");
		try {
			String encoding = "UTF-8";
			File file = new File(filePath);
			if (file.isFile() && file.exists()) {
				InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);
				BufferedReader bufferedReader = new BufferedReader(read);
				String lineTxt = null;
				while ((lineTxt = bufferedReader.readLine()) != null) {
					content.append(lineTxt + "\r\n");// txt换行
				}
				read.close();
			} else {
				System.out.println("找不到指定的文件");
			}
		} catch (Exception e) {
			System.out.println("读取文件内容出错");
			e.printStackTrace();
		}
		return content.toString();
	}

	public static void printFile(String content, String targetFile) {
		BufferedWriter bw = null;
		try {
			File file = new File(targetFile);
			if (!file.exists()) {
				file.createNewFile();
			}
			FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
			bw = new BufferedWriter(fw);
			bw.write(content);
			bw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
